﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using OA.BLL;

using OA.Core;
using OA.Core.EF;
using OA.Core.Helper;
using OA.Model;
using OA.Web.Attribute;
using OA.Web.Code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using X.PagedList;

namespace OA.Web.Areas.Member.Controllers
{
    /// <summary>
    /// 部门日志
    /// </summary>

    public class DepartmentDiaryController : BaseMemberController
    {
        private IMemoryCache _cache;
        private ICookie _cookie;
        public DepartmentDiaryController(ICookie cookie, IHttpContextAccessor accessor, IMemoryCache cache) : base(accessor, cookie, cache)
        {
            _cache = cache;
            _cookie = cookie;
        }

        [MyActionFilterAttribute("001008", "部门日志", "个人中心", true, "iconbumen1")]
        public IActionResult Index()
        {
            return View();
        }

        [MyActionFilterAttribute("001008", "部门日志")]
        public IActionResult GetData(string empName, string startTime, string endTime, int page = 1, int limit = 15)
        {
            
            string msg = string.Empty;
            List<SimpleEmployeePosition> result = GetDepartmentEmployeesByLeaderEmpID(Info.EmpID, ref msg);
            if (result == null || result.Count == 0)
            {
                ViewBag.ErrorMsg = msg;
            }
            List<string> empIDs = result.Select(m => m.EmpID).ToList();
            Expression<Func<Diary, bool>> where = m => m.Status != -1 && empIDs.Contains(m.EmpID);

            if (!string.IsNullOrWhiteSpace(empName))
            {
                where = where.AndAlso(m => m.EmpID == empName || m.EmpName == empName);
            }

            if (!string.IsNullOrWhiteSpace(startTime))
            {
                DateTime dt = DateTime.Now;
                if (DateTime.TryParse(startTime, out dt))
                {
                    string tempStr = dt.ToString("yyyy-MM-dd");
                    where = where.AndAlso(m => m.DateTime.CompareTo(tempStr) >= 0);
                }
            }

            if (!string.IsNullOrWhiteSpace(endTime))
            {
                DateTime dt = DateTime.Now;
                if (DateTime.TryParse(endTime, out dt))
                {
                    string tempStr = dt.ToString("yyyy-MM-dd");
                    where = where.AndAlso(m => m.DateTime.CompareTo(tempStr) <= 0);
                }
            }
            var list = this.dbContextFactory.DbContext.Diary.Where(where).OrderByDescending(m => m.ID).ToPagedList(page, limit);
            var myResult = new
            {
                code = "0",
                msg = "",
                count = list.TotalItemCount,
                data = list
            };
            return Json(myResult);
        }


        public List<SimpleEmployeePosition> GetDepartmentEmployeesByLeaderEmpID(string empID,ref string msg)
        {             
            var departments = this.dbContextFactory.DbContext.Department.Where(m => m.Status != -1).Select(SimpleDepartment.Map).ToList();

            List<int> myPositions= this.dbContextFactory.DbContext.EmployeePosition.Where(m => m.EmpID == empID && m.Status != -1).Select(m => m.PositionID).ToList();

            var managementDepartments = departments.Where(m => myPositions.Contains(m.LeaderPositionID)).ToList();
            if (managementDepartments.Count == 0)
            {
                msg = "您在公司中尚未担任任何管理岗位";
                return new List<SimpleEmployeePosition>() ;
            }
            List<int> managementQ = new List<int>();
            int index = 0;
            while (true)
            {
                var nextList = new List<SimpleDepartment>();
                foreach (var managementDepartment in managementDepartments)
                {
                    managementQ.Add(managementDepartment.ID);
                    var next2 = departments.Where(m => m.ParentDepartmentID == managementDepartment.ID).ToList();
                    nextList.AddRange(next2);
                }
                if (index++ > 20 || nextList.Count == 0) { break; }
                managementDepartments = nextList;
            }
            var positions = this.dbContextFactory.DbContext.Position.Where(m => m.Status != -1).ToList();
            var allPositions = positions.Where(m => managementQ.Contains(m.DepartmentID)).Select(m=>m.ID).ToList();
            var eployees = this.dbContextFactory.DbContext.EmployeePosition.Where(m => m.Status != -1).Select(SimpleEmployeePosition.Map).ToList();
            return eployees.Where(m => allPositions.Contains(m.PositionID)).ToList();

        }

        [HttpGet]
        [MyActionFilterAttribute("001008", "部门日志")]
        public IActionResult Export(string empName, string startTime, string endTime)
        {
            ViewBag.EmpName = empName;
            ViewBag.StartTime = startTime;
            ViewBag.EndTime = endTime;
            string msg = string.Empty;
            List<SimpleEmployeePosition> listEmployeePosition = GetDepartmentEmployeesByLeaderEmpID(Info.EmpID,ref msg);
            List<string> empIDs = listEmployeePosition.Select(m => m.EmpID).ToList();

            var list = this.dbContextFactory.DbContext.VEmployeeInfo.Where(m => empIDs.Contains(m.EmpID)).ToList();
            ViewBag.Employees = list.GroupBy(p => new { p.EmpID }).Select(g => g.First()).ToList();//去重
            if (!string.IsNullOrWhiteSpace(msg))
            {
                ViewBag.Msg = msg;
            }
            return View();
        }

        [HttpPost]
        [MyActionFilterAttribute("001008", "部门日志")]
        public IActionResult Export(List<string> empIDs, string empName, string startTime, string endTime)
        {
            ViewBag.EmpName = empName;
            ViewBag.StartTime = startTime;
            ViewBag.EndTime = endTime;

            if (empIDs == null || empIDs.Count == 0)
            {
                ViewBag.Msg = "请至少勾选一个需要导出日志的人员";
                return View();
            }

            string msg = string.Empty;
            var listEmployeePosition = GetDepartmentEmployeesByLeaderEmpID(Info.EmpID, ref msg);
            if (!string.IsNullOrWhiteSpace(msg))
            {
                ViewBag.Msg = msg;
                return View();
            }

            var currentSelectEmp = listEmployeePosition.Where(m => empIDs.Contains(m.EmpID)).Select(m=>m.EmpID).ToList();
            if(currentSelectEmp.Count==0)
            {
                ViewBag.Msg = "请至少勾选一个需要导出日志的人员";               
                return View();
            }

            string title = "工作日志汇总";

            string empID = Info.EmpID;
            Expression<Func<Diary, bool>> where = m => m.Status != -1 && currentSelectEmp.Contains(m.EmpID);
             

            if (!string.IsNullOrWhiteSpace(startTime))
            {
                DateTime dt = DateTime.Now;
                if (DateTime.TryParse(startTime, out dt))
                {
                    string tempStr = dt.ToString("yyyy-MM-dd");
                    where = where.AndAlso(m => m.DateTime.CompareTo(tempStr) >= 0);
                    title += $"，[开始时间:{dt.ToString2()}]";
                }
            }

            if (!string.IsNullOrWhiteSpace(endTime))
            {
                DateTime dt = DateTime.Now;
                if (DateTime.TryParse(endTime, out dt))
                {
                    string tempStr = dt.ToString("yyyy-MM-dd");
                    where = where.AndAlso(m => m.DateTime.CompareTo(tempStr) <= 0);
                    title += $"，[结束时间:{dt.ToString2()}]";
                }
            }

            var result = this.dbContextFactory.DbContext.Diary.Where(where).ToList();

            var ms = ExcelHelper.ExportDiary(title, result);

            return new FileStreamResult(ms, "application/vnd.ms-excel");

        }



    }
}